import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {UserService} from "../../services/user.service";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@IonicPage()
@Component({
  selector: 'page-up-password',
  templateUrl: 'up-password.html',
})
export class UpPasswordPage {
  public validateForm: FormGroup;//表单
  public type;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private fb: FormBuilder, private userService: UserService,
              private view: ViewController) {
    this.type = this.navParams.get('type');
    this.validateForm = this.fb.group({
      password: [null, Validators.compose([Validators.required])],
      confirmPwd: [null, [this.confirmValidator]],
    });//表单
  }

  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls.password.value) {
      return {confirm: true, error: true};
    }
  };

  updateConfirmValidator(): void {
    Promise.resolve().then(() => this.validateForm.controls['confirmPwd'].updateValueAndValidity());
  }

  updatePassword($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    if (me.type === 'password') {
      this.userService.updatePassword(me.validateForm.value.password).then(res => {
        this.dismiss()
      })
    } else if (me.type === 'pinPassword') {
      this.userService.updatePinPassword(me.validateForm.value.password).then(res => {
        this.dismiss()
      })
    }
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  dismiss() {
    this.view.dismiss()
  }

}
